package com.common.handler;

import com.common.vo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
        return new Result(
                HttpStatus.METHOD_NOT_ALLOWED.value(), // 405
                "请求方法不支持: " + ex.getMethod() + "，支持的方法: " + String.join(", ", ex.getSupportedMethods()),
                null
        );
    }

    /**
     * 处理其他运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleRuntimeException(RuntimeException ex) {
        return new Result(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                ex.getMessage(),
                null
        );
    }

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(Exception ex) {
        return new Result(
                HttpStatus.INTERNAL_SERVER_ERROR.value(),
                "服务器内部错误: " + ex.getMessage(),
                null
        );
    }
}
